import { getToken, setToken, removeToken } from '@/utils/auth'
import { login, getInfo } from '@/api/user'
import { resetRouter } from '@/router'
const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: {}
  }
}

const state = getDefaultState()

const mutations = {
  // 存token
  setToken(state, token) {
    state.token = token
    setToken(token)
  },
  // 删token
  removeToken(state) {
    state.token = null
    removeToken()
  },
  // 获取用户信息
  getUserInfo(state, data) {
    state.userInfo = data
  },
  // 删除用户信息
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async loginActions(store, data) {
    const res = await login(data)
    store.commit('setToken', res.data)
  },
  // 获取用户资料
  async getUserInfoActions(store) {
    const res = await getInfo()
    store.commit('getUserInfo', res.data.userInfo)
    // 将按钮权限挂载在window上
    // console.log(res)
    window.btnList = res.data.btnList
    return res
  },
  // 退出操作
  logout({ commit }) {
    commit('removeUserInfo')
    commit('removeToken')
    // 重置路由
    resetRouter()
    // vuex的user模块action里面调用permission模块的mutations方法
    commit('permission/setRoutes', [], { root: true })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
